package com.lmx.common.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 图片操作类
 */
public class ImgUtil {
	private static final Log log = LogFactory.getLog(ImgUtil.class);

	/**
	 * @param im
	 *            原始图像
	 * @param resizeTimes
	 *            倍数,比如0.5就是缩小一半,0.98等等double类型
	 * @return 返回处理后的图像
	 */
	public static BufferedImage zoomImage(BufferedImage im, float resizeTimes) {
		/* 原始图像的宽度和高度 */
		int width = im.getWidth();
		int height = im.getHeight();

		/* 调整后的图片的宽度和高度 */
		int toWidth = (int) (Float.parseFloat(String.valueOf(width))
				* resizeTimes);
		int toHeight = (int) (Float.parseFloat(String.valueOf(height))
				* resizeTimes);
		log.debug("toWidth:" + toWidth);
		log.debug("toWidth:" + toWidth);

		/* 新生成结果图片 */
		BufferedImage result = new BufferedImage(toWidth, toHeight,
				BufferedImage.TYPE_INT_RGB);

		result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight,
				java.awt.Image.SCALE_SMOOTH), 0, 0, null);
		return result;
	}

	/**
	 * 把图片写到磁盘上
	 * 
	 * @param im
	 * @param path
	 *            eg: /home/tiannianbao/36588_444.jpg 文件地址
	 * @param fileName
	 *            DCM1987.jpg 写入图片的名字
	 * @return
	 */
	public static boolean writeToDisk(BufferedImage im, String path) {
		String exName = path.split("\\.")[1]; // 获取拓展名
		File f = new File(path);
		try {
			ImageIO.write(im, exName, f);
			return true;
		} catch (IOException e) {
			log.error("导出缩略图失败", e);
		}
		return false;
	}

	/**
	 * 按照宽度进行等比缩放,并保存图片
	 * 
	 * @param imgFile
	 *            图片文件
	 * 
	 * @param targetWidth
	 *            缩小后的宽度
	 * 
	 * @param savePath
	 *            存储路径
	 * 
	 * @return File 存储的文件实例
	 */
	public static File zoomImgRefWidth(File imgFile, int targetWidth,
			String savePath) throws IOException {
		BufferedImage img = javax.imageio.ImageIO.read(imgFile);
		int oriWidth = img.getWidth();
		log.debug("oriWidth:" + oriWidth);
		log.debug("targetWidth:" + targetWidth);
		// 根据宽度比得到压缩率
		float resizeTimes = ((float) targetWidth) / ((float) oriWidth);
		log.debug("resizeTimes:" + resizeTimes);
		BufferedImage target = ImgUtil.zoomImage(img, resizeTimes);
		if (ImgUtil.writeToDisk(target, savePath)) {
			return new File(savePath);
		}
		return null;
	}
}
